package com.xingu.xg.exception;

import com.xingu.xg.common.consts.ComRT;
import com.xingu.xg.common.consts.ComResult;
import org.springframework.validation.FieldError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(XinGuException.class)
    public ComResult<?> runtimeExceptionHandler(XinGuException e) {
        log.error("XinGuException", e);
        return ComRT.fail(200, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ComResult<?> validationExceptionHandler(MethodArgumentNotValidException e) {
        log.error("Validation error", e);
        BindingResult bindingResult = e.getBindingResult();
        String message = bindingResult.getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .findFirst().orElse("服务器正在忙碌中...");
        return ComRT.fail(200, message);
    }

    @ExceptionHandler(RuntimeException.class)
    public ComResult<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ComRT.fail(200, "服务器正在忙碌中...");
    }
}
